unit EasyComputerPlayer;

interface

uses Player, BoardArray, Board, Types;

type
 TEasyComputerPlayer = class(TPlayer)
 protected
  function GetAvailableMoves(Board: TBoard): TPointList;
  function isMoveAvailable(Board: TBoard; i,j: integer): boolean;
  function GetProperNeighbourhood(Board: TBoard; i,j: Integer): TArrayPoint;
 public
  procedure PerfromAMove(Board: TObject); override;
  function IsOwnMovable: Boolean; override;
  constructor Create;
 end;

implementation

constructor TEasyComputerPlayer.Create;
begin
 inherited Create;
 Avatar.LoadFromFile('graph\robot.bmp');
end;

function TEasyComputerPlayer.GetProperNeighbourhood(Board: TBoard; i,j: Integer): TArrayPoint;
begin

   if Board.IsLeftNeighbourhood(i,j) then
    Result := TArrayPoint.Create(i-1, j)
   else if Board.IsRightNeighbourhood(i,j) then
    Result := TArrayPoint.Create(i+1, j)
   else if Board.IsTopNeighbourhood(i,j) then
    Result := TArrayPoint.Create(i, j-1)
   else if Board.IsBottomNeighbourhood(i,j) then
    Result := TArrayPoint.Create(i, j+1)
   else Result := nil;
end;

function TEasyComputerPlayer.isMoveAvailable(Board: TBoard; i,j: integer): boolean;
var
 Dimension: Integer;
begin
 Dimension := Length(Board.GetBoardArray);
 
 Result := Board.IsLeftNeighbourhood(i,j) or
           Board.IsRightNeighbourhood(i,j) or
           Board.IsTopNeighbourhood(i,j) or
           Board.IsBottomNeighbourhood(i,j);
end;

function TEasyComputerPlayer.GetAvailableMoves(Board: TBoard): TPointList;
var
 dimension,i,j: integer;
 output: TPointList;
begin
 output := TPointList.Create;
 dimension := Length(Board.GetBoardArray);
 i := 0;

 while (i < dimension) do
  begin
   j := 0;
   while (j < dimension) do
    begin
     if (isMoveAvailable(Board, i,j)) then
      output.Add(TArrayPoint.Create(i,j));

    inc(j);
    end;
   inc(i);
  end;
 Result := output;
end;

function TEasyComputerPlayer.IsOwnMovable: Boolean;
begin
 Result := True;
end;

procedure TEasyComputerPlayer.PerfromAMove(Board: TObject);
var
 myBoard: TBoard;
 MovesList: TPointList;
 Target, Target2: TArrayPoint;
begin
 myBoard := TBoard(Board);

 MovesList := GetAvailableMoves(myBoard);
 if (MovesList.Count > 0) then
 begin
  Target := MovesList[Random(MovesList.Count)];
  Target2 := GetProperNeighbourhood(myBoard, Target.GetX, Target.GetY);
  myBoard.PerformAMove(Point(Target.GetX, Target.GetY), Point(Target2.GetX, Target2.GetY), self);
 end;

end;

end.
